﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Activation;
using Microsoft.ManagementConsole;
using System.Windows.Forms;
using System.Drawing;
using SharpShare.Management.Mmc.Views;

namespace SharpShare.Management.Mmc.Nodes {
    public interface IExtensionInstanceSelector<TExtension> {
        object GetInstance(TExtension extension);
    }

    public class ExtensionInstanceNode<TExtension> : ScopeNode where TExtension : IExtension {
        public ExtensionInstanceNode(TExtension extension, IExtensionFactory<TExtension> factory, bool hideExpandIcon = true)
            : base(hideExpandIcon) {
            this.Extension = extension;
            this.Factory = factory;
            this.EnabledStandardVerbs = (StandardVerbs.Properties | StandardVerbs.Delete);
            this.DisplayName = extension.Name;
        }

        public IExtensionFactory<TExtension> Factory { get; private set; }
        public TExtension Extension { get; private set; }
        public IExtensionInstanceSelector<TExtension> InstanceSelector { get; set; }
        public new ExtensionNode<TExtension> Parent {
            get {
                return (ExtensionNode<TExtension>)((ScopeNode)this).Parent;
            }
        }

        protected override void OnDelete(SyncStatus status) {
            base.OnDelete(status);

            this.Factory.RemoveExtension(this.Extension);
            this.Parent.Children.Remove(this);
        }
        protected override void OnAddPropertyPages(PropertyPageCollection propertyPageCollection) {
            object selectObject = null;

            if (this.InstanceSelector != null) {
                selectObject = this.InstanceSelector.GetInstance(this.Extension);
            }

            if (selectObject == null) {
                selectObject = this.Extension;
            }

            PropertyGridPropertyPage page = new PropertyGridPropertyPage(selectObject) {
                Title = "Properties"
            };

            page.Applied += new EventHandler(PropertyGridPropertyPageApplied);
            page.Cancelled += new EventHandler(PropertyGridPropertyPageCancelled);

            propertyPageCollection.Add(page);
        }

        private void PropertyGridPropertyPageCancelled(object sender, EventArgs e) {
            if (!this.Factory.ContainsExtension(this.Extension)) {
                this.Parent.Children.Remove(this);
            } else {
                this.Parent.Refresh(this.Extension);
            }
        }

        private void PropertyGridPropertyPageApplied(object sender, EventArgs e) {
            if (!this.Factory.ContainsExtension(this.Extension)) {
                this.Factory.AddExtension(this.Extension);
            }

            this.Parent.Refresh(this.Extension);
        }

    }
}
